import logging
import time
import os
import json

def setupLogger():
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    log_path = os.path.dirname(os.getcwd()) + '/logs/'
    if not os.path.exists(log_path):
        os.makedirs(log_path)

    log_name = log_path + rq + '.log'
    logfile = log_name
    fh = logging.FileHandler(logfile, mode='w')
    fh.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger


class monitor:
    def __init__(self) -> None:
        self.name_list = {}
        self.phase = 'login'

    def update(self, name, t):
        self.save()
        if self.phase == 'login':
            return self.login(name, t)
        elif self.phase == 'logout':
            return self.logout(name, t)

    def setCurrentPhase(self, phase):
        if phase not in ['login', 'logout']:
            return -1
        self.phase = phase
        return 0

    def login(self, name, t):
        t = time.asctime( time.localtime(t) )
        if name not in self.name_list.keys():
            self.name_list[name] = {'login': t}
        else:
            return -1
        
        return 0

    def logout(self, name, t):
        t = time.asctime( time.localtime(t) )
        if name not in self.name_list.keys():
            return -1
        if 'login' in self.name_list[name].keys():
            self.name_list[name]['logout'] = t
        else:
            return -1

        return 0

    def discracted(self, name, t):
        '''
        t: detection cost time (ms)
        '''
        if name not in self.name_list.keys():
            return -1

        if 'discracted_time' not in self.name_list.keys():
            self.name_list[name]['discracted_time'] = 0

        self.name_list[name]['discracted_time'] += t

        return 0

    def save(self):
        json.dump(self.name_list, open('report.json', 'w'))


if __name__ == '__main__':
    sta = monitor()
    sta.login('孙鑫宇', time.time())
    sta.login('孙鑫宇', time.time())
    sta.logout('孙鑫宇', time.time())
    print(time.time())